package com.vincce.sport.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.ImgModel;
import com.vincce.sport.entity.ImgStorage;
import com.vincce.sport.entity.ImgTemp;
import com.vincce.sport.mapper.ImgModelMapper;
import com.vincce.sport.mapper.ImgStorageMapper;
import com.vincce.sport.mapper.ImgTempMapper;


@Controller
@RequestMapping("/imgStorage")
public class ImgStorageController extends BaseController{
	@Resource
	private ImgStorageMapper imgStorageMapper;
	@Resource
	private ImgModelMapper imgModelMapper;
	@Resource
	private ImgTempMapper imgTempMapper;

	@RequestMapping("/list")
	public String showImgStorage(Model model, Long modelId){
		ImgModel imgModel = imgModelMapper.findImgModelById(modelId);
		if(imgModel!=null){
			ImgStorage imgStorage = new ImgStorage();
			imgStorage.setTempId(imgModel.getTempId());
			imgStorage.setModelId(imgModel.getId());
			List<ImgStorage> imgStorageList = imgStorageMapper.findImgStorageByOne(imgStorage);
			if(imgStorageList!=null && imgStorageList.size()>0){
				model.addAttribute("imgStorageList", replace(imgStorageList));
			} else{
				model.addAttribute("imgStorageList", new ArrayList<ImgStorage>());
			}
			
			ImgTemp imgTemp = imgTempMapper.findImgTempById(imgModel.getTempId());
			if(imgTemp == null){
				imgTemp = new ImgTemp();
			}
			model.addAttribute("imgTemp", imgTemp);
			
			List<ImgTemp> imgTempList = imgTempMapper.findAllImgTemp();
			if(imgTempList == null){
				imgTempList = new ArrayList<ImgTemp>();
			}
		    model.addAttribute("imgTempList",imgTempList);
		    
			model.addAttribute("modelId", modelId);
			return "backstage/imgStorageList";
		} else{
			return "500";
		}
	}
	
	/**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<ImgStorage> replace(List<ImgStorage> imgStorageList){
		if(imgStorageList!=null && imgStorageList.size()>0){
			for(ImgStorage isl:imgStorageList){
				isl.setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+isl.getImgPath(), "ori"));
			}
		}
		return imgStorageList;
	}

    @RequestMapping("/insert")
    @ResponseBody
    public String insertOrUpdate(Model model, Integer demo_num, Long tempId, Long modelId, HttpServletRequest request) throws IOException{
    	Long count = 0l;
        Map<String, Object> result = new HashMap<String, Object>();
        if(demo_num != 0){
        	//添加新绑定
        	ImgModel imgModel = imgModelMapper.findImgModelById(modelId);
        	imgModel.setTempId(tempId);
        	count = imgModelMapper.updateImgModel(imgModel);
        	if(count > 0 ){
        		//删除以前的
            	ImgStorage imgStorage = new ImgStorage();
            	imgStorage.setTempId(tempId);
    			imgStorage.setModelId(modelId);
    			List<ImgStorage> imgStorageList = imgStorageMapper.findImgStorageByOne(imgStorage);
    			if(imgStorageList!=null && imgStorageList.size()>0){
    				for(ImgStorage isl:imgStorageList){
    					imgStorageMapper.deleteById(isl.getId());
    				}
    			}
    			
        		//替换内容
            	for(int i=1;i<=demo_num;i++){
            		String imgPath = "imgPath"+i;
            		String clickNum = "clickNum"+i;
            		String mark = "mark"+i;
            		
            		imgStorage = new ImgStorage();
            		if(request.getParameter(imgPath)!=null){
            			imgStorage.setImgPath(request.getParameter(imgPath).replace(SimpleStorageClient.REQUEST_URI2_PREFIX, "").replace("ori", "%s"));
            		}
            		if(request.getParameter(clickNum)!=null){
            			imgStorage.setClickNum(Integer.parseInt(request.getParameter(clickNum)));
            		}
            		if(request.getParameter(mark)!=null){
            			imgStorage.setMark(request.getParameter(mark));
            		}
            		imgStorage.setCreateTime(new Date());
            		imgStorage.setCreateUser(getCurrentUser().getId());
            		imgStorage.setModelId(modelId);
            		imgStorage.setOrderNum(i);
            		imgStorage.setTempId(tempId);
            		
            		count = imgStorageMapper.insertImgStorage(imgStorage);
            	}
            }
        }
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
    }
    
    
	@RequestMapping("/imageUpload")
	@ResponseBody 
	public String imageUpload(Model model, @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request) throws IOException{
		Boolean flag = false;
		String msg = "";
        Map<String, Object> result = new HashMap<String, Object>();
        SimpleStorageClient.StorageResult obj = new SimpleStorageClient.StorageResult(200, "");
        if (file != null && !file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
                msg = "格式不正确,只支持后缀名为.jpg或者.png的图片上传。";
            } else {
                obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
                if (obj.statusCode == 200) {
                	flag = true;
                	String path = obj.info.replaceAll("\\\\", "/");
                	result.put("img", String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+path, "ori"));
                	result.put("imgPath", path);
                }
            }
        } else{
        	msg = "请选择图片!";
        }
        result.put("suc", flag);
        result.put("msg", msg);
        return JSON.toJSONString(result);
	}

    @RequestMapping("/delete")
    @ResponseBody
    public String deleteImgStorage(Model model, Long id, HttpServletRequest request) throws IOException{
        Boolean flag = false;

        imgStorageMapper.deleteById(id);

        flag = true;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("obj", flag);
        return JSON.toJSONString(result);
    }

}
